<template>
  <div class="app-container">
    <el-form ref="searchRleationRef" :model="searchForm" :inline="true" :rules="rules"
             label-width="90px">

      <el-form-item label="问题" prop="problemId">
        <el-select v-model="searchForm.problemId" placeholder="请选择问题" filterable clearable
                   @change="handleProblemChange">
          <el-option
              v-for="problem in problemData"
              :key="problem.value"
              :label="problem.label"
              :value="problem.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="答案" prop="answerId">
        <el-select v-model="searchForm.answerId" placeholder="请选择答案" filterable clearable>
          <el-option
              v-for="answer in answerData"
              :key="answer.value"
              :label="answer.label"
              :value="answer.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
      </el-form-item>
      <el-form-item label="特征" prop="characteristicsId">
        <el-select v-model="searchForm.characteristicsId" placeholder="请选择特征" filterable clearable>
          <el-option
              v-for="characteristics in characteristicData"
              :key="characteristics.value"
              :label="characteristics.label"
              :value="characteristics.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleSearchCharacteristics">搜索</el-button>
      </el-form-item>
      <el-form-item label="疾病" prop="diseaseId">
        <el-select v-model="searchForm.diseaseId" placeholder="请选择疾病" filterable clearable>
          <el-option
              v-for="disease in diseaseData"
              :key="disease.value"
              :label="disease.label"
              :value="disease.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleSearchDisease">搜索</el-button>
        <el-button icon="Refresh" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <div ref="chartContainer" style="width: 100%; height: 90vh;"></div>
    <!-- 自定义的上下文菜单，初始时不显示 -->
    <div ref="contextReleationMenu" class="context-menu" style="display: none;">
      <el-button @click="releationDelete" type="danger" plain icon="Delete">删除关系</el-button>
    </div>

    <div ref="contextProblemNodeMenu" style="display: none;">
      <el-button @click="deleteProblemNode" type="primary" plain icon="Delete">删除问题</el-button>
    </div>
    <div ref="contextAnswerNodeMenu" style="display: none;" class="containerMenu">
      <div class="sectionMenu">
        <el-button @click="addAnswerProblemReleation" style="margin-left: 10px;" type="primary" plain icon="Plus">创建答案和问题关系</el-button>
      </div>
      <div class="sectionMenu">
        <el-button @click="addCharacteristicsReleation" style="margin-left: 10px;" type="primary" plain icon="Plus">创建答案和特征关系</el-button>
      </div>
      <div class="sectionMenu">
        <el-button @click="deleteProblemAnswerNode" style="margin-left: 10px;" type="primary" plain icon="Delete">删除答案</el-button>
      </div>
      <div class="sectionMenu">
        <el-button @click="addProblemNode" style="margin-left: 10px;" type="primary" plain icon="Edit">添加问题</el-button>
      </div>
      <div class="sectionMenu">
        <el-button @click="addCharacteristicNode" style="margin-left: 10px;" type="primary" plain icon="Add">添加特征</el-button>
      </div>
    </div>
    <div ref="contextCharacteristicsNodeMenu" style="display: none;" class="containerCharacteristicMenu">
      <div class="sectionCharacteristicMenu">
        <el-button @click="addDiseaseReleation" style="margin-left: 10px;" type="primary" plain icon="Plus">创建特征和疾病关系</el-button>
      </div>
      <div class="sectionCharacteristicMenu">
        <el-button @click="addDiseaseNode" style="margin-left: 10px;" type="primary" plain icon="Edit">添加疾病</el-button>
      </div>
      <div class="sectionCharacteristicMenu">
        <el-button @click="deleteCharacteristics"  style="margin-left: 10px;" type="primary" plain icon="Delete">删除特征</el-button>
      </div>
    </div>
    <div ref="contextDiseaseNodeMenu" style="display: none;">
      <el-button @click="deleteDiseaseNode" type="primary" plain icon="Delete">删除疾病</el-button>
    </div>


    <el-dialog :title="releationTitle" v-model="releationOpen" width="600px" append-to-body>
      <el-form ref="problemRleationRef" :model="releationForm" :inline="true" :rules="rules" label-width="90px">

        <el-form-item v-if="false" label="答案" prop="target">
          <el-select v-model="releationForm.target" placeholder="请选择答案" filterable>
            <el-option
                v-for="answer in answerData"
                :key="answer.value"
                :label="answer.label"
                :value="answer.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="问题" prop="source">
          <el-select v-model="releationForm.source" placeholder="请选择问题" filterable>
            <el-option
                v-for="problem in problemData"
                :key="problem.value"
                :label="problem.label"
                :value="problem.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitReleationForm">确 定</el-button>
          <el-button @click="cancelReleation">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改中医问题对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="problemRef" :model="form" :inline="true" :rules="rules" label-width="90px">
        <el-form-item v-if="false" label="目标点" prop="target">
          <el-select v-model="form.target" placeholder="目标点" filterable clearable>
            <el-option
                v-for="answer in answerData"
                :key="answer.value"
                :label="answer.label"
                :value="answer.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="问题类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择问题类型">
            <el-option
                v-for="dict in medical_problem_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题类别" prop="category">
          <el-select v-model="form.category" placeholder="请选择问题类别">
            <el-option
                v-for="dict in medical_problem_category"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题名称" prop="name">
          <el-input v-model="form.name" style="width: 1000px" placeholder="请输入问题名称"/>
        </el-form-item>
        <el-form-item label="问题描述" prop="description">
          <el-input type="textarea" :rows="3" style="width: 1000px" v-model="form.description"
                    placeholder="请输入问题描述"/>
        </el-form-item>
        <el-form-item label="备注" prop="memo">
          <el-input type="textarea" :rows="3" style="width: 1000px" v-model="form.memo" placeholder="请输入备注"/>
        </el-form-item>
        <el-divider content-position="center">中医问题答案信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddMedicalProblemAnswer">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteMedicalProblemAnswer">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="medicalProblemAnswerList" :row-class-name="rowMedicalProblemAnswerIndex"
                  @selection-change="handleMedicalProblemAnswerSelectionChange" ref="medicalProblemAnswer">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="答案" prop="answer" width="500">
            <template #default="scope">
              <el-input v-model="scope.row.answer" placeholder="请输入答案"/>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="memo" width="500">
            <template #default="scope">
              <el-input v-model="scope.row.memo" placeholder="请输入备注"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 添加或修改中医特征对话框 -->
    <el-dialog :title="titleCharacteristics" v-model="openCharacteristics" width="500px" append-to-body>
      <el-form ref="characteristicsRef" :model="formCharacteristics" :rules="rulesCharacteristics" label-width="80px">

        <el-form-item v-if="false" label="答案" prop="target">
          <el-select v-model="formCharacteristics.target" placeholder="请选择答案" filterable>
            <el-option
                v-for="answer in answerData"
                :key="answer.value"
                :label="answer.label"
                :value="answer.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="特征类型" prop="type">
          <el-select v-model="formCharacteristics.type" placeholder="请选择特征类型">
            <el-option
                v-for="dict in medical_characteristics_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="特征名称" prop="name">
          <el-input v-model="formCharacteristics.name" placeholder="请输入特征名称"/>
        </el-form-item>
        <el-form-item label="特征描述" prop="description">
          <el-input v-model="formCharacteristics.description" placeholder="请输入特征描述"/>
        </el-form-item>
        <el-form-item label="备注" prop="memo">
          <el-input v-model="formCharacteristics.memo" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCharacteristicsForm">确 定</el-button>
          <el-button @click="cancelCharacteristics">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改中医疾病对话框 -->
    <el-dialog :title="titleDisease" v-model="openDisease" width="500px" append-to-body>
      <el-form ref="diseaseRef" :model="formDisease" :rules="rulesDisease" label-width="80px">
        <el-form-item label="疾病类型" prop="type">
          <el-select v-model="formDisease.type" placeholder="请选择疾病类型">
            <el-option
                v-for="dict in medical_disease_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="疾病名称" prop="name">
          <el-input v-model="formDisease.name" placeholder="请输入疾病名称"/>
        </el-form-item>
        <el-form-item label="疾病描述" prop="description">
          <el-input type="textarea" :rows="3" v-model="formDisease.description" placeholder="请输入疾病描述"/>
        </el-form-item>
        <el-form-item label="备注" prop="memo">
          <el-input v-model="formDisease.memo" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDiseaseForm">确 定</el-button>
          <el-button @click="cancelDisease">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--创建答案和特征之间的关系-->
    <el-dialog :title="releationCharacteristicsTitle" v-model="releationCharacteristicsOpen" width="600px"
               append-to-body>
      <el-form ref="characteristicsRleationRef" :model="releationCharacteristicsForm" :inline="true"
               :rules="rulesCharacteristicsReleation"
               label-width="90px">

        <el-form-item v-if="false" label="答案" prop="target">
          <el-select v-model="releationCharacteristicsForm.target" placeholder="请选择答案" filterable>
            <el-option
                v-for="answer in answerData"
                :key="answer.value"
                :label="answer.label"
                :value="answer.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="特征" prop="source">
          <el-select v-model="releationCharacteristicsForm.source" placeholder="请选择特征" filterable>
            <el-option
                v-for="problem in characteristicData"
                :key="problem.value"
                :label="problem.label"
                :value="problem.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitReleationreleationCharacteristicsFormForm">确 定</el-button>
          <el-button @click="cancelReleationCharacteristicsForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!---创建疾病和特征之间的关系-->
    <el-dialog :title="releationDiseaseTitle" v-model="releationDiseaseOpen" width="600px"
               append-to-body>
      <el-form ref="diseaseRleationRef" :model="releationDiseaseForm" :inline="true" :rules="rulesDiseaseReleation"
               label-width="90px">

        <el-form-item v-if="false" label="答案" prop="target">
          <el-select v-model="releationDiseaseForm.target" placeholder="请选择答案" filterable>
            <el-option
                v-for="answer in characteristicData"
                :key="answer.value"
                :label="answer.label"
                :value="answer.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="疾病" prop="source">
          <el-select v-model="releationDiseaseForm.source" placeholder="请选择疾病" filterable>
            <el-option
                v-for="problem in diseaseData"
                :key="problem.value"
                :label="problem.label"
                :value="problem.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitReleationDiseaseFormForm">确 定</el-button>
          <el-button @click="cancelReleationDiseaseForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Releation">
import {
  problemAndAnswerList,
  listProblem,
  getProblem,
  delProblem,
  addProblem,
  updateProblem,
  delProblemAnswer
} from "@/api/medical/problem/problem.js";
import {
  listCharacteristics,
  getCharacteristics,
  delCharacteristics,
  addCharacteristics,
  updateCharacteristics,
  characteristicsList
} from "@/api/medical/characteristics/characteristics.js";
import {
  delReleation,
  listNodeAndEdge,
  makeReleation,
  queryNodeAndReleation
} from "@/api/medical/releation/releation.js";
import {
  listDisease,
  getDisease,
  delDisease,
  addDisease,
  updateDisease,
  diseaseList
} from "@/api/medical/disease/disease.js";

const {proxy} = getCurrentInstance();
const {
  medical_problem_type,
  medical_problem_start,
  medical_problem_category
} = proxy.useDict('medical_problem_type', 'medical_problem_start', 'medical_problem_category');
const {medical_characteristics_type} = proxy.useDict('medical_characteristics_type');
const {medical_disease_type} = proxy.useDict('medical_disease_type');

import {onMounted} from "vue";
import * as echarts from 'echarts';
import {ref} from "vue";

const open = ref(false);
const releationCharacteristicsOpen = ref(false);
const openCharacteristics = ref(false);
const releationDiseaseOpen = ref(false);
const openDisease = ref(false);


const loading = ref(true);

const title = ref("");
const titleCharacteristics = ref("");
const releationCharacteristicsTitle = ref("");
const releationDiseaseTitle = ref("");
const titleDisease = ref("");

const medicalProblemAnswerList = ref([]);

let contextReleationMenu = ref(null); // 用于存储自定义的右键菜单
let contextAnswerNodeMenu = ref(null);
let contextProblemNodeMenu = ref(null);
let contextCharacteristicsNodeMenu = ref(null);
let contextDiseaseNodeMenu = ref(null);
let myChart = ref({});

const problemData = ref([]);
const answerData = ref([]);
const characteristicData = ref([]);
const diseaseData = ref([]);
const releationTitle = ref("");
const releationOpen = ref(false);
const releationViewTitle = ref("");
const releationViewOpen = ref(false);

const chartContainer = ref(null);
//节点
const nodes = ref([]);
//关系
const links = ref([]);

const currentNode = ref(null);
const currentSource = ref(null);
const currentTarget = ref(null);

const data = reactive({
  form: {},
  formCharacteristics: {},
  releationForm: {},
  searchForm: {},
  releationCharacteristicsForm: {},
  releationDiseaseForm: {},
  formDisease: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: null,
    category: null,
    name: null,
    description: null,
    memo: null,
  },
  rules: {
    type: [
      {required: true, message: "问题类型不能为空", trigger: "change"}
    ],
    category: [
      {required: true, message: "问题类别不能为空", trigger: "change"}
    ],
    name: [
      {required: true, message: "问题名称不能为空", trigger: "blur"}
    ],
    description: [
      {required: true, message: "问题描述不能为空", trigger: "blur"}
    ],
    source: [
      {required: true, message: "起始节点问题不能为空", trigger: "change"}
    ],
    target: [
      {required: true, message: "结束节点问题答案不能为空", trigger: "change"}
    ],
  },
  rulesCharacteristics: {
    type: [
      {required: true, message: "特征类型不能为空", trigger: "change"}
    ],
    name: [
      {required: true, message: "特征名称不能为空", trigger: "blur"}
    ],
    description: [
      {required: true, message: "特征描述不能为空", trigger: "blur"}
    ]
  },
  rulesCharacteristicsReleation: {
    source: [
      {required: true, message: "起始节点特征不能为空", trigger: "change"}
    ],
    target: [
      {required: true, message: "结束节点问题答案不能为空", trigger: "change"}
    ],
  },
  rulesDiseaseReleation: {
    source: [
      {required: true, message: "起始节点疾病不能为空", trigger: "change"}
    ],
    target: [
      {required: true, message: "结束节点特征不能为空", trigger: "change"}
    ],
  },
  rulesDisease: {
    type: [
      {required: true, message: "特征类型不能为空", trigger: "change"}
    ],
    name: [
      {required: true, message: "特征名称不能为空", trigger: "blur"}
    ],
  }

});

const {
  queryParams,
  form,
  formCharacteristics,
  releationForm,
  searchForm,
  releationCharacteristicsForm,
  releationDiseaseForm,
  formDisease,
  rules,
  rulesCharacteristics,
  rulesCharacteristicsReleation,
  rulesDiseaseReleation,
  rulesDisease
} = toRefs(data);

const option = {
  legend: {
    data: ['问题', '答案', "特征", "疾病"]
  },
  tooltip: {},
  animationDurationUpdate: 1500,
  animationEasingUpdate: 'quinticInOut',
  series: [
    {
      type: 'graph',
      layout: 'none',
      symbolSize: 40,
      roam: true,
      label: {
        show: true
      },
      edgeSymbol: ['circle', 'arrow'],
      edgeSymbolSize: [4, 10],
      edgeLabel: {
        fontSize: 20
      },
      tooltip: {
        trigger: 'item',
        triggerOn: 'contextmenu'
      },
      categories: [
        {
          name: '问题',
          keyword: {},
          base: '问题'
        },
        {
          name: '答案',
          keyword: {},
          base: '答案'
        },
        {
          name: '特征',
          keyword: {},
          base: '特征'
        },
        {
          name: '疾病',
          keyword: {},
          base: '疾病'
        }
      ],
      data: [],
      links: [],
      // force: {
      //   repulsion: 600,
      //   edgeLength: 100
      // },
      // 监听鼠标移入事件
      emphasis: {
        focus: 'adjacency', // 相邻节点也会被高亮
        triggerOn: 'mouseover', // 触发高亮的事件
      },
      lineStyle: {
        opacity: 0.9,
        width: 2,
        curveness: 0
      }
    }
  ]
};

//挂载完成阶段进行初始化，否则找不到当前页面的容器
onMounted(() => {
  NodeAndReleation();
});

function NodeAndReleation() {
  loading.value = true;
  nodes.value = [];
  links.value = [];
  queryParams.value.releationType = 3;
  queryNodeAndReleation(queryParams.value).then(response => {
    for (var i = 0; i < response.data.nodes.length; i++) {
      let node = {};
      node.id = response.data.nodes[i].id;
      node.name = response.data.nodes[i].name;
      node.category = response.data.nodes[i].category;
      node.x = response.data.nodes[i].x;
      node.y = response.data.nodes[i].y;
      nodes.value.push(node);
    }
    for (var i = 0; i < response.data.links.length; i++) {
      let link = {};
      link.source = response.data.links[i].source;
      link.target = response.data.links[i].target;
      links.value.push(link);
    }
    loading.value = false;
    initGrap();
  });
}


function initGrap() {
  option.series[0].data = nodes.value;
  option.series[0].links = links.value;
  if (queryParams.value.problemIds) {
    if (myChart && myChart.dispose) {
      myChart.dispose();
    }
  }
  // 初始化新实例
  myChart = echarts.init(chartContainer.value);
  myChart.setOption(option);
  // console.log(chartContainer.value, 'myChart1：',myChart);

  myChart.on('contextmenu', (params) => {
    console.log("dataType:" + params.dataType);
    console.log(params);
    if (params.dataType === 'edge'
        && ((params.data.source.indexOf("PROBLEM") > -1 && params.data.target.indexOf("ANSWER") > -1)
            || (params.data.source.indexOf("CHARACTERISTIS") > -1 && params.data.target.indexOf("ANSWER") > -1)
            || (params.data.source.indexOf("DISEASE") > -1 && params.data.target.indexOf("CHARACTERISTIS") > -1))) {
      params.event.event.preventDefault();
      // 显示上下文菜单
      showContextMenu(params.event.offsetX + 15, params.event.offsetY + 110);
      //记录当前关系的开始节点和结束节点
      currentSource.value = params.data.source;
      currentTarget.value = params.data.target;

      hideContextAnswerMenu();
      hideContextProblemNodeMenu();
      hideContextCharacteristicsMenu();
      hideContextDiseaseMenu();
    } else if (params.dataType === 'node' && params.data.category === 0) {
      params.event.event.preventDefault();
      //显示node的菜单
      showContextDeleteNodeMenu(params.event.offsetX + 15, params.event.offsetY + 110);

      hideContextReleationMenu();
      hideContextAnswerMenu();
      hideContextAnswerMenu();
      hideContextDiseaseMenu();
      //记录当前点击的nodeid
      currentNode.value = params.data.id;
    } else if (params.dataType === 'node' && params.data.category === 1) {
      params.event.event.preventDefault();
      //显示node的菜单
      showContexNodetMenu(params.event.offsetX + 15, params.event.offsetY + 110);
      hideContextReleationMenu();
      hideContextProblemNodeMenu();
      hideContextCharacteristicsMenu();
      hideContextDiseaseMenu();
      //记录当前点击的nodeid
      currentNode.value = params.data.id;
    } else if (params.dataType === 'node' && params.data.category === 2) {
      params.event.event.preventDefault();
      //显示node的菜单
      showContexCharacteristicsMenu(params.event.offsetX + 15, params.event.offsetY + 110);
      hideContextReleationMenu();
      hideContextProblemNodeMenu();
      hideContextAnswerMenu();
      hideContextDiseaseMenu();
      //记录当前点击的nodeid
      currentNode.value = params.data.id;
    } else if (params.dataType === 'node' && params.data.category === 3) {
      params.event.event.preventDefault();
      //显示node的菜单
      showContexDiseaseMenu(params.event.offsetX + 15, params.event.offsetY + 110);
      hideContextReleationMenu();
      hideContextProblemNodeMenu();
      hideContextCharacteristicsMenu();
      hideContextAnswerMenu();
      //记录当前点击的nodeid
      currentNode.value = params.data.id;
    } else {
      hideContextReleationMenu();
      hideContextAnswerMenu();
      hideContextProblemNodeMenu();
    }
  });

  // 监听窗口大小变化，以更新图表尺寸
  window.addEventListener('resize', () => {
    myChart.resize();
  });
}

function showContextDeleteNodeMenu(x, y) {

  // 设置菜单的位置
  contextProblemNodeMenu.value.style.left = `${x}px`;
  contextProblemNodeMenu.value.style.top = `${y}px`;
  contextProblemNodeMenu.value.style.position = 'absolute'; // 确保是absolute或fixed
  // 显示菜单
  contextProblemNodeMenu.value.style.display = 'block';

  // 添加文档点击事件监听器，用于隐藏菜单
  document.addEventListener('click', hideContextProblemNodeMenu);
}

// 显示上下文菜单
function showContextMenu(x, y) {
  // 设置菜单的位置
  contextReleationMenu.value.style.left = `${x}px`;
  contextReleationMenu.value.style.top = `${y}px`;
  contextReleationMenu.value.style.position = 'absolute'; // 确保是absolute或fixed

  // 显示菜单
  contextReleationMenu.value.style.display = 'block';

  // 添加文档点击事件监听器，用于隐藏菜单
  document.addEventListener('click', hideContextReleationMenu);
}

// 显示上下文菜单
function showContexNodetMenu(x, y) {
  // 设置菜单的位置
  contextAnswerNodeMenu.value.style.left = `${x}px`;
  contextAnswerNodeMenu.value.style.top = `${y}px`;
  contextAnswerNodeMenu.value.style.position = 'absolute'; // 确保是absolute或fixed
  // 显示菜单
  contextAnswerNodeMenu.value.style.display = 'block';

  // 添加文档点击事件监听器，用于隐藏菜单
  document.addEventListener('click', hideContextAnswerMenu);
}

function showContexCharacteristicsMenu(x, y) {
  // 设置菜单的位置
  contextCharacteristicsNodeMenu.value.style.left = `${x}px`;
  contextCharacteristicsNodeMenu.value.style.top = `${y}px`;
  contextCharacteristicsNodeMenu.value.style.position = 'absolute'; // 确保是absolute或fixed
  // 显示菜单
  contextCharacteristicsNodeMenu.value.style.display = 'block';

  // 添加文档点击事件监听器，用于隐藏菜单
  document.addEventListener('click', hideContextCharacteristicsMenu);
}

function showContexDiseaseMenu(x, y) {
  // 设置菜单的位置
  contextDiseaseNodeMenu.value.style.left = `${x}px`;
  contextDiseaseNodeMenu.value.style.top = `${y}px`;
  contextDiseaseNodeMenu.value.style.position = 'absolute'; // 确保是absolute或fixed
  // 显示菜单
  contextDiseaseNodeMenu.value.style.display = 'block';

  // 添加文档点击事件监听器，用于隐藏菜单
  document.addEventListener('click', hideContextDiseaseMenu);
}

// 隐藏上下文菜单
function hideContextReleationMenu() {
  if (contextReleationMenu.value) {
    contextReleationMenu.value.style.display = 'none';
  }
  document.removeEventListener('click', hideContextReleationMenu);
}

function hideContextCharacteristicsMenu() {
  if (contextCharacteristicsNodeMenu.value) {
    contextCharacteristicsNodeMenu.value.style.display = 'none';
  }
  document.removeEventListener('click', hideContextCharacteristicsMenu);
}

function hideContextDiseaseMenu() {
  if (contextDiseaseNodeMenu.value) {
    contextDiseaseNodeMenu.value.style.display = 'none';
  }
  document.removeEventListener('click', hideContextDiseaseMenu);
}

//隐藏菜单
function hideContextAnswerMenu() {
  if (contextAnswerNodeMenu.value) {
    contextAnswerNodeMenu.value.style.display = 'none';
  }
  document.removeEventListener('click', hideContextAnswerMenu);
}

function hideContextProblemNodeMenu() {
  if (contextProblemNodeMenu.value) {
    contextProblemNodeMenu.value.style.display = 'none';
  }
  document.removeEventListener('click', hideContextProblemNodeMenu);
}

// 处理删除操作
function releationDelete() {
  // 这里可以编写实际的删除逻辑
  form.value.source = currentSource.value;
  form.value.target = currentTarget.value;
  delReleation(form.value).then(response => {
    proxy.$modal.msgSuccess("删除关系成功");
    //触发视图渲染
    NodeAndReleation();
  });

  // 删除后隐藏菜单
  hideContextReleationMenu();
}

function handleSearch() {

  if (!searchForm.value.problemId && !searchForm.value.answerId) {
    return;
  }
  let nodeId = "";
  if (searchForm.value.answerId) {
    nodeId = 'ANSWER' + searchForm.value.answerId;
  }
  if (!nodeId) {
    nodeId = 'PROBLEM' + searchForm.value.problemId;
  }
  const data = myChart.getOption().series[0].data;
  const nodeIndex = data.findIndex(node => node.id === nodeId);

  if (nodeIndex !== -1) {
    // 定位到节点
    myChart.dispatchAction({
      type: 'highlight',
      seriesIndex: 0,
      dataIndex: nodeIndex
    });

  }
}

function handleSearchCharacteristics() {
  if (!searchForm.value.characteristicsId) {
    return;
  }
  let nodeId = "CHARACTERISTIS" + searchForm.value.characteristicsId;

  const data = myChart.getOption().series[0].data;
  const nodeIndex = data.findIndex(node => node.id === nodeId);

  if (nodeIndex !== -1) {
    // 定位到节点
    myChart.dispatchAction({
      type: 'highlight',
      seriesIndex: 0,
      dataIndex: nodeIndex
    });

  }
}

function handleSearchDisease() {
  if (!searchForm.value.diseaseId) {
    return;
  }
  let nodeId = "DISEASE" + searchForm.value.diseaseId;

  const data = myChart.getOption().series[0].data;
  const nodeIndex = data.findIndex(node => node.id === nodeId);

  if (nodeIndex !== -1) {
    // 定位到节点
    myChart.dispatchAction({
      type: 'highlight',
      seriesIndex: 0,
      dataIndex: nodeIndex
    });

  }
}

function addAnswerProblemReleation() {
  releationForm.value.source = null;
  releationOpen.value = true;
  releationTitle.value = "关系创建";
  releationForm.value.target = currentNode.value;

}

//创建答案和特征关系
function addCharacteristicsReleation() {
  releationCharacteristicsForm.value.source = null;
  releationCharacteristicsOpen.value = true;
  releationCharacteristicsTitle.value = "关系创建";
  releationCharacteristicsForm.value.target = currentNode.value;
}


//创建特征和疾病之间的关系
function addDiseaseReleation() {
  releationDiseaseForm.value.source = null;
  releationDiseaseOpen.value = true;
  releationDiseaseTitle.value = "关系创建";
  releationDiseaseForm.value.target = currentNode.value;
}

function addProblemNode() {
  handleAdd();
  form.value.target = currentNode.value;
}

function addDiseaseNode() {
  resetDisease();
  openDisease.value = true;
  titleDisease.value = "添加疾病";
  formDisease.value.target = currentNode.value;
}

/**
 * 删除问题
 */
function deleteProblemNode() {
  const _ids = currentNode.value.replace("PROBLEM", "");
  proxy.$modal.confirm('是否确认删除此问题？').then(function () {
    return delProblem(_ids);
  }).then(() => {
    NodeAndReleation();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/**
 * 删除问题答案
 */
function deleteProblemAnswerNode() {
  const _ids = currentNode.value.replace("ANSWER", "");
  proxy.$modal.confirm('是否确认删除此问题答案？').then(function () {
    return delProblemAnswer(_ids);
  }).then(() => {
    NodeAndReleation();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/**
 * 删除特征
 */
function deleteCharacteristics() {
  const _ids = currentNode.value.replace("CHARACTERISTIS", "");
  proxy.$modal.confirm('是否确认删除中医特征？').then(function () {
    return delCharacteristics(_ids);
  }).then(() => {
    NodeAndReleation();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/**
 * 删除疾病
 */
function deleteDiseaseNode() {
  const _ids = currentNode.value.replace("DISEASE", "");
  proxy.$modal.confirm('是否确认删除中医疾病？').then(function () {
    return delDisease(_ids);
  }).then(() => {
    NodeAndReleation();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/**
 * 问题列表
 */
function getProblemList() {
  problemAndAnswerList().then(response => {
    problemData.value = [];
    for (var i = 0; i < response.data.length; i++) {
      let problem = {};
      problem.value = response.data[i].id;
      problem.label = response.data[i].name;
      problemData.value.push(problem);
    }
  });
}

function getCharacteristicsList() {
  characteristicData.value = [];
  characteristicsList().then(response => {
    for (var i = 0; i < response.data.length; i++) {
      let characteristic = {};
      characteristic.value = response.data[i].id;
      characteristic.label = response.data[i].name;
      characteristicData.value.push(characteristic);
    }
  });
}


function getDiseaseDataList() {
  diseaseData.value = [];
  diseaseList().then(response => {
    for (var i = 0; i < response.data.length; i++) {
      let disease = {};
      disease.value = response.data[i].id;
      disease.label = response.data[i].name;
      diseaseData.value.push(disease);
    }
  })
}

/**
 * 切换问题
 */
function handleProblemChange(problemId) {
  releationForm.value.source = null;
  getProblem(problemId).then(response => {
    answerData.value = [];
    for (var i = 0; i < response.data.medicalProblemAnswerList.length; i++) {
      let answer = {};
      answer.value = response.data.medicalProblemAnswerList[i].id;
      answer.label = response.data.medicalProblemAnswerList[i].answer;
      answerData.value.push(answer);
    }
  });
}

/**
 * 绑定关系
 */
function submitReleationForm() {

  proxy.$refs["problemRleationRef"].validate(valid => {
    if (valid) {
      releationForm.value.target = releationForm.value.target;
      releationForm.value.source = 'PROBLEM' + releationForm.value.source;
      makeReleation(releationForm.value).then(response => {
        releationOpen.value = false;
        proxy.$modal.msgSuccess("新建关系成功");
        NodeAndReleation();
      });
    }
  });
}

/**
 * 绑定答案和特征之间的关系
 */
function submitReleationreleationCharacteristicsFormForm() {
  proxy.$refs["characteristicsRleationRef"].validate(valid => {
    if (valid) {
      releationCharacteristicsForm.value.target = releationCharacteristicsForm.value.target;
      releationCharacteristicsForm.value.source = 'CHARACTERISTIS' + releationCharacteristicsForm.value.source;
      makeReleation(releationCharacteristicsForm.value).then(response => {
        releationCharacteristicsOpen.value = false;
        proxy.$modal.msgSuccess("新建关系成功");
        NodeAndReleation();
      });
    }
  });
}

/**
 * 创建特征和疾病之间的关系
 */
function submitReleationDiseaseFormForm() {
  proxy.$refs["diseaseRleationRef"].validate(valid => {
    if (valid) {
      releationDiseaseForm.value.target = releationDiseaseForm.value.target;
      releationDiseaseForm.value.source = 'DISEASE' + releationDiseaseForm.value.source;
      makeReleation(releationDiseaseForm.value).then(response => {
        releationDiseaseOpen.value = false;
        proxy.$modal.msgSuccess("新建关系成功");
        NodeAndReleation();
      });
    }
  });
}


/**
 * 取消创建关系
 */
function cancelReleation() {
  releationOpen.value = false;
  releationForm.value = {
    source: null,
    target: null,
    problemId: null
  };
  proxy.resetForm("problemRleationRef");
}

/**
 * 取消创建答案和特征的关系
 */
function cancelReleationCharacteristicsForm() {
  releationCharacteristicsOpen.value = false;
  releationCharacteristicsForm.value = {
    source: null,
    target: null
  };
  proxy.resetForm("characteristicsRleationRef");
}

/**
 * 取消创建特征和答案之间的关系
 */
function cancelReleationDiseaseForm() {
  releationDiseaseOpen.value = false;
  releationDiseaseForm.value = {
    source: null,
    target: null
  };
  proxy.resetForm("diseaseRleationRef");
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["problemRef"].validate(valid => {
    if (valid) {
      form.value.medicalProblemAnswerList = medicalProblemAnswerList.value;
      if (form.value.id != null) {
        updateProblem(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          //刷新一下关系页面
          NodeAndReleation();
          getProblemList();
        });
      } else {
        addProblem(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          //刷新一下关系页面
          NodeAndReleation();
          getProblemList();
        });
      }
    }
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加中医问题";
}


// 表单重置
function reset() {
  form.value = {
    id: null,
    type: null,
    category: null,
    name: null,
    target: null,
    description: null,
    memo: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  medicalProblemAnswerList.value = [];
  proxy.resetForm("problemRef");
}

/** 中医问题答案添加按钮操作 */
function handleAddMedicalProblemAnswer() {
  let obj = {};
  obj.answer = "";
  obj.memo = "";
  medicalProblemAnswerList.value.push(obj);
}

/** 中医问题答案删除按钮操作 */
function handleDeleteMedicalProblemAnswer() {
  if (checkedMedicalProblemAnswer.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的中医问题答案数据");
  } else {
    const medicalProblemAnswers = medicalProblemAnswerList.value;
    const checkedMedicalProblemAnswers = checkedMedicalProblemAnswer.value;
    medicalProblemAnswerList.value = medicalProblemAnswers.filter(function (item) {
      return checkedMedicalProblemAnswers.indexOf(item.index) == -1
    });
  }
}

/** 中医问题答案序号 */
function rowMedicalProblemAnswerIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 复选框选中数据 */
function handleMedicalProblemAnswerSelectionChange(selection) {
  checkedMedicalProblemAnswer.value = selection.map(item => item.index)
}

function addCharacteristicNode() {
  resetCharacteristics();
  openCharacteristics.value = true;
  titleCharacteristics.value = "添加中医特征";
  formCharacteristics.value.target = currentNode.value;
}

// 表单重置
function resetCharacteristics() {
  formCharacteristics.value = {
    id: null,
    type: null,
    name: null,
    description: null,
    memo: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("characteristicsRef");
}


function submitCharacteristicsForm() {
  proxy.$refs["characteristicsRef"].validate(valid => {
    if (valid) {
      if (formCharacteristics.value.id != null) {
        updateCharacteristics(formCharacteristics.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openCharacteristics.value = false;
          //刷新一下关系页面
          NodeAndReleation();
          getCharacteristicsList();
        });
      } else {
        addCharacteristics(formCharacteristics.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openCharacteristics.value = false;
          //刷新一下关系页面
          NodeAndReleation();
          getCharacteristicsList();
        });
      }
    }
  });
}

/**
 * 添加疾病
 */
function submitDiseaseForm() {
  proxy.$refs["diseaseRef"].validate(valid => {
    if (valid) {
      if (formDisease.value.id != null) {
        updateDisease(formDisease.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openDisease.value = false;
          //刷新一下关系页面
          NodeAndReleation();
          getDiseaseDataList();
        });
      } else {
        addDisease(formDisease.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openDisease.value = false;
          //刷新一下关系页面
          NodeAndReleation();
          getDiseaseDataList();
        });
      }
    }
  });
}

function cancelCharacteristics() {
  openCharacteristics.value = false;
  resetCharacteristics();
}

function cancelDisease() {
  openDisease.value = false;
  resetDisease();
}

function resetDisease() {
  formDisease.value = {
    id: null,
    type: null,
    name: null,
    description: null,
    memo: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("diseaseRef");
}

function resetSearch() {
  proxy.resetForm("searchRleationRef");
}


getDiseaseDataList();
getCharacteristicsList();
getProblemList();
</script>
<style scoped>
.containerMenu {
  width: 200px; /* 宽度 */
  height: 300px; /* 高度 */
  position: relative; /* 设置为相对定位，以便内部元素可以相对于它定位（虽然在这个例子中不是必需的） */
  border: 1px solid #ccc; /* 可选：给容器添加边框以便更清楚地看到它 */
  background-color: #fff; /* 背景色，可能需要与边框色对比 */
  border-radius: 8px;
}

.sectionMenu {
  margin-top: 10px;
  width: 100%; /* 宽度占满父容器 */
  height: 50px; /* 高度为父容器高度的四分之一 */
  border-bottom: 1px solid #ccc; /* 可选：给每个区域底部添加边框，以区分它们 */
  /* 如果不想在最后一个区域显示底部边框，可以添加一个类来覆盖这个样式 */
}

.sectionMenu:last-child {
  border-bottom: none; /* 移除最后一个区域的底部边框 */
}


.containerCharacteristicMenu {
  width: 200px; /* 宽度 */
  height: 180px; /* 高度 */
  position: relative; /* 设置为相对定位，以便内部元素可以相对于它定位（虽然在这个例子中不是必需的） */
  border: 1px solid #ccc; /* 可选：给容器添加边框以便更清楚地看到它 */
  background-color: #fff; /* 背景色，可能需要与边框色对比 */
  border-radius: 8px;
}

.sectionCharacteristicMenu {
  margin-top: 12px;
  width: 100%; /* 宽度占满父容器 */
  height: 50px; /* 高度为父容器高度的四分之一 */
  border-bottom: 1px solid #ccc; /* 可选：给每个区域底部添加边框，以区分它们 */
  /* 如果不想在最后一个区域显示底部边框，可以添加一个类来覆盖这个样式 */
}

.sectionCharacteristicMenu:last-child {
  border-bottom: none; /* 移除最后一个区域的底部边框 */
}
</style>